package com.xwj.juc.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 该同步组件在同一时刻，只允许至多两个线程同时访问，超过两个线程的访问将被阻塞
 * 获取或释放的时候采用自旋的方式实现锁共享
 * @author xwj
 * @date 2020/5/9
 */
public class TwinsLock implements Lock {

    private static class Sync extends AbstractQueuedSynchronizer {
        Sync(int count) {
            setState(count);
        }

        @Override
        protected int tryAcquireShared(int acquires) {
            // 自旋
            for (; ; ) {
                int state = getState();
                int newState = state - acquires;
                if (newState < 0 || compareAndSetState(state, newState)) {
                    return newState;
                }
            }
        }

        @Override
        protected boolean tryReleaseShared(int releases) {
            for (; ; ) {
                int state = getState();
                int newState = state + releases;
                if (compareAndSetState(state, newState)) {
                    return true;
                }
            }
        }
    }

    private final Sync sync = new Sync(2);

    @Override
    public void lock() {
        sync.acquireShared(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        sync.releaseShared(1);
    }

    @Override
    public Condition newCondition() {
        return null;
    }

    public static void main(String[] args) {
        final TwinsLock twinsLock = new TwinsLock();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                twinsLock.lock();
                try {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(Thread.currentThread().getName());
                    TimeUnit.SECONDS.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    twinsLock.unlock();
                }
            }, "testTwinsLock" + i).start();
        }
    }
}
